import sys
import matplotlib.pyplot as plt
import numpy as np
from mz_date import MZ_Date
from db_handler import DB_handler
from calendarWindow import Calendar
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FC

class ArtistFig(QWidget):
    def __init__(self):
        super(ArtistFig, self).__init__()
        self.main_layout=QVBoxLayout()
        # 解决无法显示中文
        plt.rcParams['font.sans-serif'] = ['SimHei']
        # 解决无法显示负号
        plt.rcParams['axes.unicode_minus'] = False
        # self.draw()
        self.setLayout(self.main_layout)

    def create_fig(self,dates,y1,y2,s_min=0,s_max=14):
        """
        生成图
        :param dates: 日期列表
        :param y1: 安排工时
        :param y2:  自填工时
        :param s_min:  工时下限
        :param s_max:   工时上限
        :return:
        """
        fig = plt.figure(figsize=(15, 4))  # (figsize=(10, 4))
        ax = fig.add_subplot(1, 1, 1)

        x = [i for i in range(len(dates))]
        nx = np.array(x)

        ny1 = np.array(y1)
        ny2 = np.array(y2)
        plt.plot(x, y1, '-or', linewidth=0.2, markersize=4)
        plt.plot(x, y2, '--o', color='limegreen', linewidth=0.4, markersize=4)
        plt.subplots_adjust(wspace=0, bottom=0.3, top=0.9)
        ax.set_xticks(x)
        ax.set_xticklabels(dates, rotation=-90)
        plt.tick_params(axis='x', labelsize=8)
        plt.fill_between(nx, ny1, ny2,
                         color='gray', alpha=0.2)  # 最小最大值

        canvas = FC(fig)
        canvas.draw()
        return canvas



class DepartmentStatisticalWindow(QWidget):

    def __init__(self,select_start_date=None,select_end_date=None):
        super(DepartmentStatisticalWindow, self).__init__()
        self.mz_date=MZ_Date()
        today=self.mz_date.getToday()
        self.select_start_date= select_start_date if select_start_date else today
        self.select_end_date= select_end_date if select_end_date else today
        self.select_data_list=[]  #选择的日期范围之间的所有日期列表
        self.all_department_radio=[]
        self.selected_departments=[]  #
        self.department_per_project_map={}  #{}{'01美术':{'proj_ylm':[task1,task2,...],'02模型':{'proj_ylm':[task1,task2,task3...],...}}
        self.slipt_department_per_project_map={}  #拆分每一天后的部门-项目-task map信息

        self.handler = DB_handler()
        self.db_project_name_map=self.handler.project_map #{'proj_gjwd': ['古剑网大', 'GJWD'], 'proj_xmm': ['致我们甜甜的小美满_BJ', 'XMM'],
        self.btn_style='''QPushButton{color:black}
                                  QPushButton:hover{color:#FF7F24}
                                  QPushButton{background-color:#CFCFCF}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:10px}
                                  QPushButton{padding:5px 1px}'''
        self.clear_btn_style='''QPushButton{color:black}
                                  QPushButton:hover{color:#FF7F24}
                                  QPushButton{background-color:#CFCFCF}
                                  QPushButton{border:15px}
                                  QPushButton{border-radius:10px}
                                  QPushButton{padding:5px 1px}'''
        self.check_style = '''QCheckbox:hover{color :##FF7F24}
                              QCheckbox{background-color:#CFCFCF}
                              QCheckbox{padding:1px 1px}
                                '''
        # self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.sicon = QIcon('bu.png')
        self.setWindowIcon(self.sicon)
        self.project_font=QFont('',13,65)
        self.setWindowTitle('各部门信息')
        self.setMinimumWidth(1000)
        self.main_layout=QHBoxLayout()

        self.left_layout=QVBoxLayout()
        self.date_layout=QVBoxLayout()
        self.date_layout.setAlignment(Qt.AlignTop)
        self.date_layout.setContentsMargins(0,30,0,0)
        self.date_layout.setSpacing(12)
        self.start_date_btn=QPushButton(self.select_start_date)
        self.start_date_btn.setStyleSheet(self.btn_style)
        self.start_date_btn.clicked.connect(self._choose_startday)
        self.end_date_btn=QPushButton(self.select_end_date)
        self.end_date_btn.setStyleSheet(self.btn_style)
        self.end_date_btn.clicked.connect(self._choose_endday)
        # self.OK_btn=QPushButton('确认')
        # self.OK_btn.setStyleSheet(self.btn_style)
        # self.OK_btn.clicked.connect(self._get_all_data)
        self.date_layout.addWidget(self.start_date_btn)
        self.date_layout.addWidget(self.end_date_btn)
        # self.date_layout.addWidget(self.OK_btn)
        self.quick_layout=QVBoxLayout()
        self.quick_layout.setSpacing(12)
        self.quick_layout.setAlignment(Qt.AlignTop)
        self.quick_layout.setContentsMargins(0,20,0,0)
        self.last_month_btn=QPushButton('上月')
        self.last_month_btn.setStyleSheet(self.btn_style)
        self.last_month_btn.clicked.connect(self._set_last_month)
        self.this_month_btn=QPushButton('本月')
        self.this_month_btn.setStyleSheet(self.btn_style)
        self.this_month_btn.clicked.connect(self._set_current_month)
        self.next_month_btn=QPushButton('下月')
        self.next_month_btn.setStyleSheet(self.btn_style)
        self.next_month_btn.clicked.connect(self._set_next_month)
        self.last_week_btn=QPushButton('上周')
        self.last_week_btn.setStyleSheet(self.btn_style)
        self.last_week_btn.clicked.connect(self._set_last_week)
        self.this_week_btn=QPushButton('本周')
        self.this_week_btn.setStyleSheet(self.btn_style)
        self.this_week_btn.clicked.connect(self._set_current_week)
        self.next_week_btn=QPushButton('下周')
        self.next_week_btn.setStyleSheet(self.btn_style)
        self.next_week_btn.clicked.connect(self._set_next_week)

        self.quick_layout.addWidget(self.last_month_btn)
        self.quick_layout.addWidget(self.this_month_btn)
        self.quick_layout.addWidget(self.next_month_btn)
        self.quick_layout.addWidget(self.last_week_btn)
        self.quick_layout.addWidget(self.this_week_btn)
        self.quick_layout.addWidget(self.next_week_btn)

        self.date_layout.addWidget(self.start_date_btn)
        self.date_layout.addWidget(self.end_date_btn)
        self.department_layout=QVBoxLayout()
        self.department_layout.setAlignment(Qt.AlignTop)
        self.department_layout.setContentsMargins(0,50,0,30)
        self.clear_btn=QPushButton('清空')
        self.clear_btn.setStyleSheet(self.clear_btn_style)
        self.clear_btn.clicked.connect(self._clear_checkbox)
        self.department_layout.addWidget(self.clear_btn)
        self.init_deparments()
        self.left_layout.addLayout(self.date_layout)
        self.left_layout.addLayout(self.quick_layout)
        self.left_layout.addLayout(self.department_layout)

        self.hs = QSplitter(Qt.Horizontal)
        self.hs.setStyleSheet('QSplitter::handle { background-color: #CFCFCF }')
        self.sc = QScrollArea()
        self.sc.setStyleSheet('QScrollBar{width:5px}')
        self.mid_frame=QFrame()#QWidget()#QScrollArea()#QFrame()
        self.mid_frame.setMinimumHeight(5500)
        self.mid_frame.setMinimumWidth(800)
        self.mid_layout=QVBoxLayout()
        self.mid_layout.setAlignment(Qt.AlignTop)
        self.mid_frame.setLayout(self.mid_layout)
        self.sc.setWidget(self.mid_frame)

        # self.right_layout=QVBoxLayout()
        # self.task_list=QListWidget()
        # self.task_list.setMinimumWidth(30)

        # self.task_list.setMaximumWidth(100)
        # self.right_layout.addWidget(self.task_list)
        self.help=QTextBrowser()
        self.init_help()
        self.help.setMaximumWidth(100)
        self.hs.addWidget(self.sc)
        self.hs.addWidget(self.help)
        # self.hs.addWidget(self.task_list)

        self.hs.setStretchFactor(0, 8)
        self.hs.setStretchFactor(1, 2)
        self.main_layout.addLayout(self.left_layout)
        # self.main_layout.addWidget(self.sc)
        # self.main_layout.addWidget(self.hs)
        # self.main_layout.addLayout(self.right_layout)
        self.main_layout.addWidget(self.hs)
        self.setLayout(self.main_layout)


    def _clear_mid_frame(self):
        if self.mid_frame.children():
            for i in self.mid_frame.children():
                # print('mid_frame child:',i)

                if isinstance(i, FC) or isinstance(i, QLabel):
                    i.deleteLater()



    # def _get_all_data(self):
    #     """
    #     获取选定日期内的所有信息
    #     :return:
    #     """
    #     start_day=self.start_date_btn.text()
    #     end_day =self.end_date_btn.text()
    #     delta=self.mz_date.delta_date(start_day,end_day)
    #
    #     self.select_start_date=start_day if delta> 0 else end_day
    #     self.select_end_date=end_day if delta> 0 else start_day
    #
    #     self.select_data_list = self.mz_date.getAlldaysInStartEndDay(self.select_start_date,
    #                                                                  self.select_end_date)  # 获取日期列表
    #
    #     self._clear_mid_frame()
    #
    #
    #
    #     artists = self.handler.get_department_artists(department)
    #     print(artists)
    #
    #     department_ori_data, department_assigned_data = self.handler.get_department_data(department, start_date, end_date)
    #
    #
    #     try:
    #         all_task_info_list=self.handler.select_task_in_dates(self.select_start_date,self.select_end_date)
    #     except Exception as _get_all_data_ERR:
    #         print('_get_all_data_ERR:', str(_get_all_data_ERR))
    #     if all_task_info_list:
    #         # print('_get_all_data 003.1:')
    #         self.department_per_project_map=self.handler.get_all_department_per_project_map(all_task_info_list)#
    #         all_splited_tasks = self.handler.split_all_tasks(all_task_info_list)
    #         self.slipt_department_per_project_map=self.handler.get_all_department_per_project_map(all_splited_tasks)#
    #         # print('_get_all_data 004:')
    #         try:
    #             self._show_hot(self.selected_departments,self.slipt_department_per_project_map)
    #         except Exception as _show_hot_ERR:
    #             print('_show_hot_ERR:',str(_show_hot_ERR))

    def get_department_convas(self,department):
        """
        获取选定日期内的指定部门的数据
        :return:
        """
        department_convas={}
        start_day=self.start_date_btn.text()
        end_day =self.end_date_btn.text()
        delta=self.mz_date.delta_date(start_day,end_day)

        self.select_start_date=start_day if delta> 0 else end_day
        self.select_end_date=end_day if delta> 0 else start_day

        self.select_data_list = self.mz_date.getAlldaysInStartEndDay(self.select_start_date,
                                                                     self.select_end_date)  # 获取日期列表

        # artists = self.handler.get_department_artists(department)
        # print(artists)
        department_ori_data, department_assigned_data = self.handler.get_department_data(department, self.select_start_date, self.select_end_date)
        print('get_department_convas 003')
        for artist,date_workhour in department_assigned_data.items():
            artistfig=ArtistFig()
            dates=[]
            assigned_workhour_list=[]
            artist_workhour_list=[]
            # print('get_department_convas:',artist,date_workhour)
            for i in date_workhour:

                date=i[0]
                show_workhour=i[1]
                s_assigned_workhour,s_artist_workhour=show_workhour.split('_')
                dates.append(i[0])
                assigned_workhour_list.append(float(s_assigned_workhour))
                artist_workhour_list.append(float(s_artist_workhour))

            convas= artistfig.create_fig(dates,assigned_workhour_list,artist_workhour_list)
            department_convas[artist]=convas

        return department_convas

        # 选择
    def choose(self):
        """
         选择部门
        :param department:
        :return:
        """
        self._clear_mid_frame()
        sender = self.sender()
        selected_department = sender.text()
        try:
            all_convas = self.get_department_convas(selected_department)
            for artist, convas in all_convas.items():
                artist_fig_layout=self.create_artist_figlayout(artist,convas)
                self.mid_layout.addLayout(artist_fig_layout)
        except Exception as choose_ERR:
            print('choose_ERR:', str(choose_ERR))
        # print(fig_map)

    def create_artist_figlayout(self, artist, convas):
        fig_layout = QHBoxLayout()
        fig_layout.setSpacing(0)
        fig_layout.setAlignment(Qt.AlignTop)
        project_label = QLabel(artist)
        project_label.setFont(self.project_font)
        project_label.setMaximumWidth(130)
        project_label.setStyleSheet('background:#CFCFCF')
        project_label.setAlignment(Qt.AlignCenter)
        project_label.setMinimumHeight(173)
        fig_layout.addWidget(project_label)
        fig_layout.addWidget(convas)
        return fig_layout

    def _clear_checkbox(self):
        for i in self.all_department_radio:
            i.setCheckState(Qt.Unchecked)
        self.selected_departments = []


    #日期选择
    def _choose_startday(self):
        self.calender=Calendar()
        self.calender.dateSignal.connect(self._set_startday)
        self.calender.show()

    def _set_startday(self,date):
        self.select_start_date=date
        self.start_date_btn.setText(date)

    def _choose_endday(self):
        self.calender=Calendar()
        self.calender.dateSignal.connect(self._set_endday)
        self.calender.show()

    def _set_endday(self,date):
        self.select_end_date=date
        self.end_date_btn.setText(date)


    #设置日期
    def _set_last_week(self):
        self.select_start_date,self.select_end_date=self.mz_date.get_last_week()
        self.select_data_list=self.mz_date.getAlldaysInStartEndDay(self.select_start_date,self.select_end_date)
        self.start_date_btn.setText(self.select_start_date)
        self.end_date_btn.setText(self.select_end_date)
        # self._get_all_data()

    def _set_current_week(self):
        self.select_start_date,self.select_end_date=self.mz_date.get_current_week()
        self.select_data_list=self.mz_date.getAlldaysInStartEndDay(self.select_start_date,self.select_end_date)
        self.start_date_btn.setText(self.select_start_date)
        self.end_date_btn.setText(self.select_end_date)
        # self._get_all_data()

    def _set_next_week(self):
        self.select_start_date,self.select_end_date=self.mz_date.get_next_week()
        self.select_data_list=self.mz_date.getAlldaysInStartEndDay(self.select_start_date,self.select_end_date)
        self.start_date_btn.setText(self.select_start_date)
        self.end_date_btn.setText(self.select_end_date)
        # self._get_all_data()


    def _set_last_month(self):
        self.select_start_date,self.select_end_date=self.mz_date.get_last_month()
        self.select_data_list=self.mz_date.getAlldaysInStartEndDay(self.select_start_date,self.select_end_date)
        self.start_date_btn.setText(self.select_start_date)
        self.end_date_btn.setText(self.select_end_date)
        # self._get_all_data()

    def _set_current_month(self):
        self.select_start_date,self.select_end_date=self.mz_date.get_current_month()
        self.select_data_list=self.mz_date.getAlldaysInStartEndDay(self.select_start_date,self.select_end_date)
        self.start_date_btn.setText(self.select_start_date)
        self.end_date_btn.setText(self.select_end_date)
        # self._get_all_data()

    def _set_next_month(self):
        self.select_start_date,self.select_end_date=self.mz_date.get_next_month()
        self.select_data_list=self.mz_date.getAlldaysInStartEndDay(self.select_start_date,self.select_end_date)
        self.start_date_btn.setText(self.select_start_date)
        self.end_date_btn.setText(self.select_end_date)
        # self._get_all_data()

    #初始化部门
    def init_deparments(self):
        departments=['01美术','02模型','03跟踪','04动画','05场景','06灯光','07特效一','07特效二','08合成一','08合成二',
        '09包装','10剪辑','11调色','12TD','13虚拟']
        for i in departments:
            radio=QRadioButton(i)
            radio.setStyleSheet("QRadioButton:hover{color:#FF7F24}"
                                   "QRadioButton{border-radius:5px}"
                                   "QRadioButton{background-color:#CFCFCF}")

            radio.clicked.connect(self.choose)
            self.all_department_radio.append(radio)
            self.department_layout.addWidget(radio)
        

    #帮助
    def init_help(self):
        text='说明：\n\n红色为安排工时，绿色为自填工时'
        self.help.setText(text)

if __name__ == '__main__':
    app=QApplication(sys.argv)
    d=DepartmentStatisticalWindow()
    d.show()
    sys.exit(app.exec_())